import { login, getInfo, logout, getAllCompany } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),//从util中获取保存的token
    name: '',//用户名
    avatar: 'static/img/profile.png',//头像
    roles: [],//角色权限，用于动态生成路由
    companyId: "",//公司id
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_COMPANYID: (state, companyId) => {
    state.companyId = companyId
  },
}

const actions = {
  // 登录
  Login({ commit }, userInfo) {

    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login(username, password).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取用户信息
  getUserInfo({ commit, state }) {

    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { userInfo } = response.data
        if (userInfo && userInfo.roles.length > 0) { // 验证返回的roles是否是一个非空数组
          commit('SET_ROLES', userInfo.roles)
        } else {
          return reject('验证失败，请重新登录。')
        }

        commit('SET_NAME', userInfo.name)
        commit('SET_AVATAR', userInfo.avatar)

        // 如果是超级管理员，获取所有公司列表,并将公司id设置第一个公司的id
        if (userInfo.companyId == '0') {
          getAllCompany().then(response => {
            const companyList = response.data.resList
            commit('SET_COMPANYID', companyList[0].id)
            // 在这里调用resolve(userInfo)
            resolve(userInfo);
          })
        } else {
          commit('SET_COMPANYID', userInfo.companyId)
          // 否则直接调用resolve(userInfo)
          resolve(userInfo);
        }
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 更新公司编号
  updateCompanyId({ commit }, companyId) {
    //设置公司id
    commit('SET_COMPANYID', companyId)
  },


  // 登出
  logout({ commit, state }) {

    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken(); // must remove  token  first
        resetRouter();
        commit('RESET_STATE')
        resolve()
        location.reload() // To prevent bugs from vue-router
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 删除token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

